/**
 * 身份验证-中间件
 */

export default () => {
    return async (ctx, next) => {
        // 身份验证
        const authorization = ctx.header.authorization;
        if (authorization) {
            const token = authorization.split(' ')[1]
            if (token) {
                const result = await ctx.server.helper.context.token.verify(token)
                if (result) {
                    ctx.tokenstr = token;
                    ctx.userInfo = result;
                    await next();
                } else {
                    ctx.$response({
                        code: 401,
                        msg: ctx.$locale('unauthorizedAccess')
                    })
                }
            } else {
                ctx.$response({
                    code: 401,
                    msg: ctx.$locale('unauthorizedAccess')
                }) 
            }
        } else {
            ctx.$response({
                code: 401,
                msg: ctx.$locale('unauthorizedAccess')
            })
        }
    }
}